package com.bbzn.device.client.service.emq.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbzn.device.client.constant.MongoDbConstant;
import com.bbzn.device.client.dataobject.Device;
import com.bbzn.device.client.dataobject.HealthDataHis;
import com.bbzn.device.client.service.DeviceService;
import com.bbzn.device.client.service.EmqStrategy;
import com.bbzn.device.client.service.SimpleMongoService;
import com.bbzn.device.client.utils.OptionalBean;
import com.bbzn.device.client.utils.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @Author: wulongbo
 * @Date : 2021/4/9 11:19
 * @Version 1.0
 */
@Component
public class EmqRateStrategy implements EmqStrategy {

    @Autowired
    private SimpleMongoService simpleMongoService;

    @Autowired
    private DeviceService deviceService;

    // 心率信息
    @Override
    public String emqAction(String payLoad) {
        try {
            JSONObject jsonObject = JSON.parseObject(payLoad);
            String imei = jsonObject.getString("imei");
            if (!OptionalBean.ofNullable(imei).isPresent()) {
                return "json解析错误";
            }
            Double rate = jsonObject.getDouble("rate");
            if (!OptionalBean.ofNullable(rate).isPresent()) {
                return "json解析错误";
            }
            /**
             * 数据类型 0 心率 1 计步 2 电量 3 室内温度 4 血氧 5 室外温度 6 海拔 7 湿度 8 空气质量
             */
            HealthDataHis healthDataHis = new HealthDataHis();
            healthDataHis.setImei(imei);
            healthDataHis.setDataValue(rate.toString());
            healthDataHis.setDataType(0);
            healthDataHis.setCreateTime(System.currentTimeMillis());   //new Timestamp(System.currentTimeMillis())
            healthDataHis.setCreatedBy("emq");
            simpleMongoService.insert(healthDataHis, MongoDbConstant.HEALTH_DATA);


            Device deviceInfo = new Device();
            deviceInfo.setImei(imei);
            deviceInfo.setRate(rate);
            deviceService.updateByImeiSelective(deviceInfo);
        } catch (Exception e) {
            return "获取心率失败！";
        }
        return "获取心率成功！";
    }
}
